
// var WXBizDataCrypt = require('../../utils/cryptojs/RdWXBizDataCrypt.js');
// pages/personal-center/personal-center.js

import {
	userCenter,
	login
} from '../../utils/request/apiurl'
import api from '../../utils/request/api'
const app = getApp();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		userData: {},
		uid: null,
		latitude:'',//纬度
		longitude:'',//经度
		role: 0, //0不是快递员，1是快递员
		// isColonel:0,//团长
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if(wx.getStorageSync('userInfo')!=''){
			this.setData({
				uid: wx.getStorageSync('userInfo').uid,
			})
		}
		this.getData()
		// console.log(wx.getStorageSync('userInfo').role)
		if( wx.getStorageSync('userInfo').role!=undefined){
			this.setData({
				role: wx.getStorageSync('userInfo').role
			})
		}
		
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		// console.log(wx.getStorageSync('userInfo'))
		if(wx.getStorageSync('userInfo')!=''){
			this.setData({
				uid: wx.getStorageSync('userInfo').uid,
				// role: wx.getStorageSync('userInfo').role
			})
		}
		this.getData()
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		wx.showNavigationBarLoading() //在标题栏中显示加载
		this.onLoad()
		setTimeout(function() {
			wx.hideNavigationBarLoading() //完成停止加载
			wx.stopPullDownRefresh() //停止下拉刷新
		}, 1500);
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	//获取用户信息
	getData() {
    if (!this.data.uid){
      return
    }	
		var source = {
			uid: this.data.uid || wx.getStorageSync('userInfo').uid
		}
		// console.log(source)
    api.post(userCenter.userData, source).then(res => {
			// console.log(res)
			var userInfo=wx.getStorageSync('userInfo')
			userInfo['isColonel'] = res.isColonel;
			userInfo['isRealname'] = res.isRealname;
			userInfo['isPayPassword'] = res.isPayPassword;
			// userInfo['isColonel'] = res.isColonel //0不是团长，1是团长
      userInfo['role'] = res.role; //0不是快递员，1是快递员
      userInfo['rank'] = res.rank; //0不是快递员，1是快递员
			userInfo['sellCount'] = res.sellCount;
			userInfo['phone'] = res.phone;
			wx.setStorageSync('userInfo', userInfo);
			this.setData({
				userData: res,
			})
			// console.log(wx.getStorageSync('userInfo'))
    }).catch(err => {
      //判断openid是否存在,不存在清除缓存
      if (err.message.indexOf("openid为空") !== -1) {
        console.log("==============>")
        wx.clearStorageSync()
      }
      console.log("catch", err.message)
			// wx.showToast({
			// 	title: '暂未登录，请前去登录',
			// 	icon: 'none',
			// 	duration: 2000
			// })
		})
	},
	// 个人信息
	personalInfo() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../personalInfo/personalInfo'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 电话客服
	telService() {
		// if(wx.getStorageSync('userInfo')!=''){
			api.post(userCenter.servicePhone).then(res => {
				wx.makePhoneCall({
					phoneNumber:res.text
				})
			}).catch(err => {
				wx.showToast({
					title: err.message,
					icon: 'none'
				})
			})
		// }
		// else{
		// 	wx.showToast({
		// 		title: '暂未登录，请前去登录',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// }
		
	},
	// 我的订单
	orderDetail(e) {
		if(wx.getStorageSync('userInfo')!=''){
			let type = e.currentTarget.dataset['type']
			wx.navigateTo({
				url: '../myOrder/myOrder?type=' + type
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 我的收益
	toProfit() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../personal-profit/personal-profit'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 我的积分
	toIntegral() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../personal-integral/personal-integral'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 我的余额
	toBalance() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../personal-balance/personal-balance'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 充值
	recharge() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../recharge/recharge'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 我的团队
	toTeam() {
		if(wx.getStorageSync('userInfo')!=''){
			if(this.data.userData.isColonel==1){
				wx.navigateTo({
					url: '../personal-team/personal-team'
				})
			}else{
				wx.showToast({
					title: '您还不是团长,请去申请',
					icon: 'none',
					duration: 2000
				})
				// wx.navigateTo({
				// 	url: '../application-header/application-header'
				// })
			}
			
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 我的优惠券
	toCoupon() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../personal-coupon/personal-coupon'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 常见问题
	commonProblem() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../common-problem/common-problem'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 团长申请
	applicationHeader() {
		if(wx.getStorageSync('userInfo')!=''){
			if(this.data.userData.isColonel==0){
				wx.navigateTo({
					url: '../application-header/application-header'
				})
			}else if(this.data.userData.isColonel==1){
				wx.showToast({
					title: '您已经成为团长了哦',
					icon: 'none',
					duration: 2000
				})
			}
			
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 收货地址
	receiveingAdress() {
		if(wx.getStorageSync('userInfo')!=''){
			wx.navigateTo({
				url: '../receiveing-adress/receiveing-adress'
			})
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 订单配送
	toCourier() {
		if(wx.getStorageSync('userInfo')!=''){
			if(wx.getStorageSync('userInfo').role==1){
				wx.navigateTo({
					url: '../myOrder-courier/myOrder-courier'
				})
			}
		}else{
			wx.showToast({
				title: '暂未登录，请前去登录',
				icon: 'none',
				duration: 2000
			})
		}
		
	},
	// 在线客服
	onLineService() {
		// wx.navigateTo({
		//  url:'../service-chat/service-chat'
		// })
	},
	// 获取位置
	getLocation(userInfo) {	
		// console.log(userInfo,'userInfouserInfo')
		var _this=this
	    wx.getLocation({
	      type: 'wgs84',
	      success: function (res) {
	        // console.log(res);
			if(res.errMsg=='getLocation:ok'){
				userInfo['latitude']=res.latitude
				userInfo['longitude']=res.longitude
				// var latitude = res.latitude
				// var longitude = res.longitude
				// console.log(userInfo)
				_this.loginList(userInfo)
			}
			
	      }
	    })
	  },

	loginList(userInfo) {
		// console.log(userInfo)
		wx.login({
			success: function(res) {
        console.log(res, 'resresres')
        // return false
				if (res.code) {
          console.log(res)
					//发起网络请求
					var options = {
						code: res.code,
						// userInfo:userInfo,
						nickName: userInfo.nickName,
						gender: userInfo.gender,
						avatarUrl: userInfo.avatarUrl,
						country: userInfo.country,
						province: userInfo.province,
						language: userInfo.language,
						city: userInfo.city,
						latitude:userInfo.latitude,
						longitude:userInfo.longitude,
						uid: wx.getStorageSync('user').TJuid || null,
					};
					// console.log(options)
					api.get(login, options).then(res => {
						console.log(res,'调用登录接口')
          //拿到session_key实例化WXBizDataCrypt（）这个函数在下面解密用
          // var pc = new WXBizDataCrypt(appId, res.data.session_key)
          //获取解密后的uniod
          // var data = pc.decryptData(res.encryptedData, res.iv)
						var userInfo = {}
						userInfo['uid'] = res.id;                
						userInfo['link'] = res.isLink;
						userInfo['rank'] = res.rank;
            userInfo['openid'] = res.openid;
            userInfo['xcxOpenid'] = res.xcxOpenid;
						userInfo['isPayPassword'] = res.isPayPassword;
						userInfo['sellCount'] = res.sellCount;
						userInfo['phone'] = res.phone;
						// userInfo['isColonel'] = res.isColonel //0不是团长，1是团长
						// userInfo['role'] = res.role; //0不是快递员，1是快递员
            wx.setStorageSync('userInfo', userInfo);
            console.log("wx:login", res)
						wx.showToast({
							title: '登录成功',
							icon: 'none'
						})
						// console.log(wx.getStorageSync('userInfo').userInfo)
						// that.getData()
						wx.switchTab({
							url: '../personal-center/personal-center'
						})
						
					}).catch(err => {
						wx.showToast({
							title: err.message,
							icon: 'none'
						})
					})
				} else {
					wx.showToast({
						title: "登录失败",
						icon: "none",
						duration: 1000
					});
				}
			}
		})
	},
	// 登录
  getUserInfo: function (res) {
    console.log("用户授权", res)
		const hasAuthorize = wx.getStorageSync('hasAuthorize');
		if (res.detail.userInfo) {
			this.getLocation(res.detail.userInfo)
			wx.setStorageSync('hasAuthorize', true);
			// this.loginList(res.detail.userInfo);
			wx.setStorageSync('Info', res.detail);
			this.onLoad()
			wx.switchTab({
				url: '../home/home'
			})
		} else {
			wx.showToast({
				title: '请先授权',
				icon: 'none',
				duration: 3000
			})
		}
	},

})
